<?php

namespace App\Services\Game;

use App\DTOS\Admin\UserRoleDTO;
use App\Models\Game\UserMember;
use App\Models\Game\UserRole;
use App\Utils\MyLog;

class UserRoleService
{
    /**
     * @param UserRoleDTO $userRoleDTO
     * @return \Illuminate\Contracts\Pagination\LengthAwarePaginator|null
     */
    public function paginate(UserRoleDTO $userRoleDTO){

        $model = UserRole::query();
        $page = $userRoleDTO->getPage();
        $pageSize = $userRoleDTO->getLimit();
        $memberIds = $userRoleDTO->getMemids();
        $memberId = $userRoleDTO->getMemid();

        $isOnline = $userRoleDTO->getIsOnline();
        $id = $userRoleDTO->getId();
        $nick = $userRoleDTO->getNick();
        $username = $userRoleDTO->getUsername();
        $createTimeBegin = $userRoleDTO->getCreateTimeBegin();
        $createTimeEnd = $userRoleDTO->getCreateTimeEnd();
        $minLevel = $userRoleDTO->getMinLevel();
        $maxLevel = $userRoleDTO->getMaxLevel();
        $ids = $userRoleDTO->getIds();
        $zoneId = $userRoleDTO->getZoneId();
        $customerId = $userRoleDTO->getCustomerId();
        $nicks = $userRoleDTO->getNicks();//角色列表

        MyLog::info('$nick'.json_encode($nicks));
        MyLog::info('$ids'.json_encode($ids));

        if ($ids){
            $idlist = explode("\n",$ids);
            $model->whereIn('id',$idlist);
        }
        if ($isOnline!=null && $isOnline!='all'){
            $model->where('isOnline',$isOnline);
        }
        if ($id!=null){
            $model->where('id',$id);
        }
        if ($createTimeBegin){
            $model->where('createtime','>=',strtotime($createTimeBegin));
        }
        if ($createTimeEnd){
            $model->where('createtime','<=',strtotime($createTimeEnd));
        }
        if ($memberIds!==null){
            $model->whereIn('memid',$memberIds);
        }
        if ($memberId!==null){
            $model->where('memid',$memberId);
        }
        if ($nick!=null){
            $model->where('nick','like',"%$nick%");
        }
        if ($minLevel) {
            $model->where('level','>=',$minLevel);
        }
        if ($maxLevel) {
            $model->where('level','<=',$maxLevel);
        }
        if ($zoneId){
            $model->where('zoneId',$zoneId);
        }
        $searchMember = false;
        if ($customerId){
            $searchMember = true;
        }
        if ($username){
            $searchMember = true;
        }
        if ($nicks){
            $nicksList = explode("\n",$nicks);
            $model->whereIn('nick',$nicksList);
        }
        if ($searchMember){
            $userMemberModel = UserMember::query();
            if ($username){
                $userMemberModel->where('username','like',"%$username%");
            }
            if ($customerId){
                $userMemberModel->where('openid',$customerId);
            }
            $memberIds = $userMemberModel->pluck('id')->toArray();
            if (empty($memberIds)){
                return null;
            }
            $model->whereIn('memid',$memberIds);
        }

        return $model->with(['member'=>function($member){
            $member->select(['id','username','openid','areaid']);
        }])->orderByDesc('id')->paginate($pageSize,$userRoleDTO->getFields(),'page',$page);

    }


    /**
     * @param $id
     * @param string[] $fields
     * @return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model|null
     */
    public function getById($id,$fields = ['*'])
    {
        return UserRole::query()->with('member')->select($fields)->find($id);
    }


    public function getUserInfo($id)
    {
        // 只查询必要的字段，减少数据传输量
        return UserRole::query()
            ->with('member')
            ->find($id);
    }

    public function getUserBaseInfo($id)
    {
        // 只查询必要的字段，减少数据传输量
        return UserRole::query()
            ->with('member')
            ->select([
                'id', 'memid', 'nick', 'job', 'sex', 'level',
                'createtime', 'logintime', 'isOnline',
                'money', 'status', 'baseAttr', 'baseAtkAttr',
                'combat', 'bag', 'pet','tickData'
            ])
            ->find($id);
    }

    /**
     * @param $ids
     * @param array $fields
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getByIds($ids,$fields = ['*'])
    {
       return UserRole::query()->whereIn('id',$ids)->select($fields)->get();
    }

    /** 检测角色ID是否存在,返回不存在的角色ID数组
     * @param array $roleIds
     * @return array
     */
    public function checkRoleExists($roleIds=[])
    {
        $UserRoleDTO = new UserRoleDTO(['page'=>1,'limit'=>9999999]);
        $UserRoleDTO->setFields(['id']);
        $paginate = $this->paginate($UserRoleDTO);
        $userRoles = $paginate->items();
        $existsIds = collect($userRoles)->pluck('id')->unique()->toArray();
        return array_unique(array_values(array_diff($roleIds,$existsIds)));
    }

}
